<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/9
 * Time: 11:11
 */

namespace common\business\ifs;

use common\consts\CommonResources;
use common\models\Log;
use yii\db\ActiveRecord;
use Yii;
use yii\db\Exception;
use yii\helpers\Json;

class DbActionWithLog extends DbLog
{

    /**
     * @param $record ActiveRecord
     * @return bool
     */
    public function doActionSafe($record)
    {
        $log = new Log();
        $log->action = CommonResources::ACTION_MSG($this->getActionName(), 'Record');
        $log->memo = Json::encode($record->attributes);
        return $this->doActionWithLogSafe($record, $log);
    }

    /**
     * @param $record ActiveRecord
     * @param $log Log
     * @return bool
     */
    public function doActionWithLogSafe($record, $log)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$record->save()) {
                $dbErrorMsg = Json::encode($record->getErrors());
                $this->addError('SaveRecordWithLog', $dbErrorMsg);
                $log->memo = $log->memo . ' | ' . CommonResources::ACTION_FAIL_MSG('Save', 'Record', $dbErrorMsg);
                $transaction->rollBack();
                return false;
            }
            if (!$log->save()) {
                $dbErrorMsg = Json::encode($log->getErrors());
                $this->addError('SaveRecordWithLog', $dbErrorMsg);
                $log->memo = $log->memo . ' | ' . CommonResources::ACTION_FAIL_MSG('Save', 'Record', $dbErrorMsg);
                Yii::error(CommonResources::ACTION_FAIL_MSG('Save', 'Log', $log->memo));
                $transaction->rollBack();
                return false;
            }
            $transaction->commit();
            return true;
        } catch (Exception $ex) {
            $this->addError('SaveRecordWithLog', $ex->getMessage());
            return false;
        }
    }
}